
package com.mc.lp.database.service.handler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;

import com.mc.lp.database.service.handler.event.IEvent;
import com.mc.lp.database.service.handler.exception.EventHandlingException;

/**
 * event handler class.
 * @author deepak
 *
 */
public abstract class AbstractEventHandler<T,E extends EventResponse> implements EventHandler{
	public Logger LOG =null;
	private Class<T> clazz;
	@SuppressWarnings("unchecked")
	public AbstractEventHandler(){
		/**
		 * general check to see if client has register its services or not
		 */
		if(getEventType()==null){
			throw new RuntimeException("Must register cache service name, see getServiceType() method");
		}
		Type type = getClass().getGenericSuperclass();
		ParameterizedType paramType = (ParameterizedType) type;
		clazz = (Class<T>) paramType.getActualTypeArguments()[0];
		setLogger();
	}
	
	public abstract E handleEvent(IEvent event) throws EventHandlingException;
	private void setLogger(){
		LOG= Logger.getLogger(getClazz());
	}

	public Logger getLOG() {
		return LOG;
	}

	public void setLOG(Logger lOG) {
		LOG = lOG;
	}

	public Class<T> getClazz() {
		return clazz;
	}

	public void setClazz(Class<T> clazz) {
		this.clazz = clazz;
	}
	
	@Override
	public String toString() {
		return "[Event Handler : "+getClazz()+"]";
	}
	/**
	 * return callable instance of handler. 
	 */
	public Callable<EventResponse> getCallable(final IEvent event) {
		return new Callable<EventResponse>() {
			public EventResponse call() throws Exception {
				return handleEvent(event);
			}
		};
	}
}